package com.ruhaly.sandianke.data.service.impl;

import android.app.Service;
import android.content.Context;
import android.os.Vibrator;

import com.ruhaly.common_lib.base.CustomThrowable;
import com.ruhaly.sandianke.data.service.ILocation;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2015/12/4.
 */
public class LocationImpl implements ILocation {

    public TencentLocationRequest request;
    public TencentLocationManager locationManager;
    public MyLocationListener mMyLocationListener;

    public Vibrator mVibrator;

    @Override
    public Observable<TencentLocation> getBdLocation(final Context context, final int level) {
        return Observable.create((Observable.OnSubscribe<TencentLocation>) subscriber -> {
            try {
                request = TencentLocationRequest.create();
                locationManager = TencentLocationManager.getInstance(context);
                request.setInterval(0);//定位周期
                request.setRequestLevel(level);//返回信息详细度
                mMyLocationListener = new MyLocationListener(subscriber);
                mVibrator = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
                int error = locationManager.requestLocationUpdates(request, mMyLocationListener);
                if (error != 0) {
                    locationManager.removeUpdates(mMyLocationListener);
                    subscriber.onError(new CustomThrowable("定位失败,errorCode:" + error));
                }
            } catch (Exception e) {
                locationManager.removeUpdates(mMyLocationListener);
            }
        }).subscribeOn(Schedulers.trampoline()).observeOn(AndroidSchedulers.mainThread());
    }


    public class MyLocationListener implements TencentLocationListener {
        Subscriber subscriber;

        public MyLocationListener(Subscriber subscriber) {
            this.subscriber = subscriber;
        }

        @Override
        public void onLocationChanged(TencentLocation tencentLocation, int error, String reason) {
            if (TencentLocation.ERROR_OK == error) {
                subscriber.onNext(tencentLocation);
                locationManager.removeUpdates(mMyLocationListener);
                subscriber.onCompleted();
                // 定位成功
            } else {
                // 定位失败
                locationManager.removeUpdates(mMyLocationListener);
                subscriber.onError(new CustomThrowable(reason + ",errorCode:" + error));
            }

        }

        @Override
        public void onStatusUpdate(String s, int i, String s1) {

        }
    }
}
